<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=employees')">导入</el-button>
          <el-button size="small" type="danger" @click="dialogVisible=true">导出</el-button>
          <el-button size="small" type="primary" :disabled="checkPermission('POINT-USER-ADD')" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" sortable="" width="60px" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                slot="reference"
                v-imageerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="row.staffPhoto?PopCode(row.staffPhoto):showCodeDialog=false"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry |formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="{row}">
              <el-switch :value="row.enableState===1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editEmployee(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="checkPermission('point-user-delete')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-pagination
            layout="total,sizes,prev, pager, next,jumper"
            :total="pageSetting.total"
            :page-size="pageSetting.size"
            :page-sizes="[2,5,10,50]"
            @current-change="currentChange"
            @size-change="sizeChange"
          />
        </el-row>
        <AddEmployee :show-dialog.sync="showDialog" @addUser="loadPage" />
        <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <el-row type="flex" justify="center">
            <el-button size="small" type="danger" @click="exportEunm">导出当前页员工信息</el-button>
            <el-button size="small" type="danger" @click="exportAllEunm">导出所有的员工信息</el-button>
          </el-row>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">放弃</el-button>
          </span>
        </el-dialog>
        <el-dialog title="二维码" :visible.sync="showCodeDialog" @opened="showQRcode">
          <el-row type="flex" justify="center">
            <canvas ref="myCanvas" />
          </el-row>
        </el-dialog>

      </el-card>

    </div>
  </div>
</template>

<script>
import { getUser, delEmployee } from '@/api/employees'
import AddEmployee from './components/add-Employee'
import AssignRole from './components/assign-role'
import EmployeeEnum from '@/api/constant/employees'
import QrCode from 'qrcode'
// import { formatDate } from '@/filters'
// import { formatDate } from '@/filters'
// import employeesEnum from '@/api/constant/employees'
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      checkList: [],
      showRoleDialog: false,
      showCodeDialog: false,
      dialogVisible: false,
      showDialog: false,
      imgUrl: '',
      userId: '',
      list: [],
      pageSetting: {
        page: 1,
        size: 5,
        total: 166
      }
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    PopCode(url) {
      this.showCodeDialog = true
      this.imgUrl = url
    },
    showQRcode() {
      QrCode.toCanvas(this.$refs.myCanvas, this.imgUrl)
    },
    exportAllEunm() {
      this.ExportInformation({ page: 1, size: this.pageSetting.total })
      this.$message.success('导出成功')
      setTimeout(() => {
        this.dialogVisible = false
      }, 800)
    },
    editEmployee(id) {
      this.userId = id
      this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },
    exportEunm() {
      this.ExportInformation(this.pageSetting)
    },
    handleClose() {
      this.dialogVisible = false
    },
    async loadPage() {
      const { rows, total } = await getUser(this.pageSetting)
      console.log(rows, total)
      this.list = rows
      this.pageSetting.total = total
    },
    async delEmployee(id) {
      try {
        await this.$confirm('确认删除吗')
        await delEmployee(id)
        await this.$message('删除成功')
        await this.loadPage()
      } catch (error) {
        console.log(error)
      }
    },
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.loadPage()
    },
    sizeChange(newSize) {
      this.pageSetting.size = newSize
      this.loadPage()
    },
    async ExportInformation(page) {
      const dictionary = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const excel = await import('@/vendor/Export2Excel')

      const { rows } = await getUser(page)
      const data = rows.map(item => {
        const arr = []
        Object.keys(dictionary).map(key => {
          if (item[dictionary[key]]) {
            if ((dictionary[key] === 'timeOfEntry' || dictionary[key] === 'correctionTime')) {
              item[dictionary[key]] = item[dictionary[key]].split('T')[0]
            }
            if (dictionary[key] === 'formOfEmployment') {
              const obj = EmployeeEnum.hireType.find(element => element.id === item[dictionary[key]])
              item[dictionary[key]] = obj.value
            }
          } else {
            item[dictionary[key]] = '未知'
          }
          arr.push(item[dictionary[key]])
        })
        return arr
      })
      console.log(data)
      // console.log(excel)
      excel.export_json_to_excel({
        header: Object.keys(dictionary),
        data,
        filename: '员工信息表',
        autoWidth: true,
        bookType: 'xlsx'
      })
      this.$message.success('导出成功')
      setTimeout(() => {
        this.dialogVisible = false
      }, 800)
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>
</style>
